<script setup>
import { ref, watch } from 'vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useUser } from '@/pinia-store/user';
import { uploadFileApi } from '@/api/common.js';
import { fileLinkToName } from '@/utils/tool.js';

const emit = defineEmits(['update:value', 'change']);

const props = defineProps({
  text: {
    type: String,
    default: '点击上传附件'
  },
  fileName: {
    type: String,
    default: 'file'
  },
  maxCount: {
    type: Number,
    default: 20
  },
  multiple: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  value: {
    type: Array,
    default: () => {
      return []
    }
  },
  bucket: {
    type: String,
    default: 'worldgroupoa'
  },
});

watch(() => props.value, () => {
  init()
}, {
  deep: true
})

const fileList = ref([])
const customRequest = (file) => {
  if (props.value.length >= props.maxCount) {
    fileList.value.splice(fileList.value.length - 1, 1)
    emit('change', file)
    emit('update:value', [...props.value])
    return message.warning(`最多只能上传${props.maxCount}个文件`)
  }
  let formData = new FormData()
  formData.append(props.fileName, file.file)
  uploadFileApi(props.bucket, formData).then(({data:res}) => {
    emit('change', file)
    emit('update:value', [...props.value, res.data])
  }).catch(() => {
    fileList.value.splice(fileList.value.length - 1, 1)
    emit('change', file)
    emit('update:value', [...props.value])
  })
}
const handleChange = (info) => {
  if (info.file.status==='removed') {
    let fileUrls = fileList.value.map(item => {
      return item.url
    })
    emit('update:value', fileUrls)
    return
  }
}

const filePerview = (file) => {
  window.open(file.response.data)
}

const init = () => {
  fileList.value = props.value.map(item => {
    return {
      url: item,
      name: fileLinkToName(item),
      response: {
        code: 0,
        data: item
      }
    }
  })
}
</script>

<template>
  <a-upload
    v-model:file-list="fileList"
    :name="props.fileName"
    :customRequest="customRequest"
    :maxCount="props.maxCount"
    :multiple="props.multiple"
    :disabled="props.disabled"
    :headers="{'Token': useUser().token}"
    :action="''"
    @change="handleChange"
    @preview="filePerview"
  >
    <a-button :disabled="props.disabled">
      <upload-outlined></upload-outlined>
      {{ props.text }}
    </a-button>
  </a-upload>
</template>
